<?php
namespace Home\Controller;

use Utuo\ForegroundController;

class VoteController extends ForegroundController {
	public function _init() {
		layout(false);
	}
	public function indexAction($sid){
		$condation=array(
			'status'=>1,
			'is_deleted'=>0	
		);
		$vote=M('form_vote')->where($condation)->select();
		foreach ($vote as &$v)
		{
			$v['url']=U('Vote/show',array('sid'=>$sid,'id'=>$v['id']));
		}
		$this->assign("vote",$vote)->display();
	}
	public function showAction($sid,$id){
		$condation=array(
			'status'=>1,
			'is_deleted'=>0,
			'cid'=>$sid,
			'id'=>$id		
		);
		C('TOKEN_ON',false);
		$data=M('FormVote')->where($condation)->field('id,title,pic,select_options,select_items,desc')->find();
		$data['answer']=M('FormVoteItem')->where('form_vote_id=%d',$data['id'])->field('id,answer,pic')->select();
		$data['select_options']=$data['select_options']?"checkbox":"radio";
		$open_id=$this->open_id;
		$this->assign("open_id",$open_id);
		$this->assign('vote',$data);
		$this->display();
	}
	public function saveRecordAction(){
		C('TOKEN_ON',false);
		$form_vote_id=I('form_vote_id');
		$openid=$this->open_id;
		$vote=M('form_vote')->where("id =".$form_vote_id)->find();
		$voteItems=M('form_vote_item')->where("form_vote_id =".$form_vote_id)->field('id')->select();
		$time=floor(time()/(3600*24))*(3600*24);
        $count=M('form_vote_record')->where("form_vote_id =".$form_vote_id." and uid ='".$openid."' and create_time > $time and create_time < $time+3600*24")->count();
      
	   if($count<$vote['vote_times']){
			$m=D('form_vote_record');
			$selected=implode(I('selected'),',');
			if($m->create())
			{    $m->selected=$selected;
			     $m->uid=$openid;
			     $flag=($m->add() and M('form_vote_item')->where('id in ('.$selected.')')->setInc('hits',1) and 
			     $total=M('form_vote_record')->where('form_vote_id='.$form_vote_id)->count());
			     foreach ($voteItems as $v)
			     {  $i=$v['id'];
			     	$data[$i][]=M('form_vote_record')->where("FIND_IN_SET($i,selected)")->count();
			     }
			     if($flag)
			     {
			     	$this->ajaxReturn(array("error"=>0,"msg"=>$vote['result_text'],"total"=>$total,"count"=>$data));
			     }
			}else {
				$this->ajaxError();
			}
		}else {
			$this->ajaxError('已超过每日投票次数，请明天再来!');
		}
	
	}
	public function setVoteAction(){
		
	}
	
}